package com.wofish.oauth.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;

@Slf4j
public class JWTUtil {

    // 过期时间2小时
    public static final long EXPIRE_TIME = 2*60 * 60 * 1000;

    // 过期时间3小时
    public static final int TOKEN_EXPIRE_TIME = 3*60 * 60 * 1000;

    // 过期时间15天
    public static final int REFRESH_TOKEN_EXPIRE_TIME = 15*24*60 * 60 * 1000;

    /**
     * 生成签名,5min后过期
     *
     * @param uid 用户名
     * @param secret   用户的密码
     * @return 加密的token
     */
    public static String sign(String appId, Long uid, String secret) {
        Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
        Algorithm algorithm = Algorithm.HMAC256(secret);
        // 附带username信息
        return JWT.create()
                .withClaim("appId",appId)
                .withClaim("uid", uid)
                .withExpiresAt(date)
                .sign(algorithm);
    }

    /**
     * 校验token是否正确
     *
     * @param token  密钥
     * @param secret 用户的密码
     * @return 是否正确
     */
    public static boolean verify(String token, String appId, Long uid, String secret) {
        try {
            Algorithm algorithm = Algorithm.HMAC256(secret);
            JWTVerifier verifier = JWT.require(algorithm)
                    .withClaim("appId",appId)
                    .withClaim("uid", uid)
                    .build();
            DecodedJWT jwt = verifier.verify(token);
        } catch (JWTVerificationException exception){
            //Invalid signature/claims
            log.error("verify:{}",exception);
            return false;
        }
        return true;
    }

    /**
     * 获得token中的信息无需secret解密也能获得
     *
     * @return token中包含的用户名
     */
    public static String getUsername(String token) {
        DecodedJWT jwt = JWT.decode(token);
        return jwt.getClaim("uid").asString();
    }

}
